package com.yhk.wuchat.common.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yhk.wuchat.common.user.dao.UserDao;
import com.yhk.wuchat.common.user.domain.entity.User;
import com.yhk.wuchat.common.user.service.UserService;
import com.yhk.wuchat.common.user.service.WXMsgService;
import com.yhk.wuchat.common.user.service.adapter.TextBuilder;
import com.yhk.wuchat.common.user.service.adapter.UserAdapter;
import com.yhk.wuchat.common.websocket.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/4/3 17:12
 * @注释
 */
@Service
@Slf4j
public class WXMsgServiceImpl implements WXMsgService {
    @Resource
    private UserDao userDao;
    @Resource
    private UserService userService;
    @Value("${wx.mp.callback}")
    private String callback;
    @Resource
    @Lazy
    private WxMpService wxMpService;
    @Resource
    private WebSocketService webSocketService;
    /**
     * openId和事件码的关系映射，等待授权的映射
     */
    private static final ConcurrentHashMap<String,Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();
    public static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    /**
     * 用户扫码成功
     * @param wxMpXmlMessage
     * @return
     */
    @Override
    public WxMpXmlOutMessage scan(WxMpXmlMessage wxMpXmlMessage) {
        //获取登录的用户
        String fromUser = wxMpXmlMessage.getFromUser();
        Integer code = getEventKey(wxMpXmlMessage);
        log.info("用户事件码,{}",code);
        if (Objects.isNull(code)){
            log.warn("事件码为空");
            return null;
        }
        User user = userDao.getByOpenId(fromUser);
        boolean registered = Objects.nonNull(user);
        //如何判断用户是否已经授权过了，查看用户是否有头像信息
        boolean authorized = registered&&StrUtil.isNotBlank(user.getAvatar());
        //用户已注册并授权就不用再向公众号推送授权信息了
        if (registered&& authorized){
            //登陆成功逻辑，通过code找到连接推送消息
            webSocketService.scanLoginSuccess(code, user.getId());
            return null;
        }
        //用户未注册
        if(!registered){
            //注册逻辑
            User insert = UserAdapter.buildUsersave(fromUser);
            userService.register(insert);
        }
        //推送链接让用户授权
        WAIT_AUTHORIZE_MAP.put(fromUser,code);
        webSocketService.waitAuthorize(fromUser, code);
        String authorizeUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        log.info("AppId: {}", wxMpService.getWxMpConfigStorage().getAppId());
        log.info("Callback: {}", callback);
        log.info("Encoded Callback: {}", URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        log.info("Authorize URL: {}", authorizeUrl);
        return  TextBuilder.build("请点击登录: <a href=\""+authorizeUrl+"\">登录</a>",wxMpXmlMessage);
    }

    /**
     * 用户授权
     * @param userInfo
     */
    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getByOpenId(openid);
        log.info("用户授权信息:{}",userInfo);
        log.info("用户信息:{}",user);
        //更新用户信息
        if(StrUtil.isBlank(user.getAvatar())){
            //补全用户信息
            fillUserInfo(user.getId(),userInfo);
        }
        Integer code = WAIT_AUTHORIZE_MAP.remove(openid);
        //通过code找到连接进行登录
        webSocketService.scanLoginSuccess(code, user.getId());
    }

    /**
     * 补全用户信息
     * @param id
     * @param userInfo
     */
    private void fillUserInfo(Long id, WxOAuth2UserInfo userInfo) {
        User user = UserAdapter.buildAuthorizeUser(id, userInfo);
        //在授权的过程中同时更新最新的用户信息到数据库中
        userDao.updateById(user);
    }

    /**
     * 获取事件码
     * @param wxMpXmlMessage
     * @return
     */
    private Integer getEventKey(WxMpXmlMessage wxMpXmlMessage) {
        try {
            //获取事件码
            String eventKey = wxMpXmlMessage.getEventKey();
            String code=eventKey.replace("qrscene_","" );
            return Integer.valueOf(code);
        } catch (NumberFormatException e) {
            log.error("获取事件码失败", wxMpXmlMessage.getEventKey(),e);
            return null;
        }
    }
}
